package cn.ac.zing.server.hj212.stater;

import cn.ac.zing.server.hj212.node.NodeContainer;
import cn.ac.zing.server.util.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.UUID;

@Component
public abstract class AbstractStarter implements Starter{

	protected JSONObject config;

	public LinkedList<NodeContainer> nodes;

	public AbstractStarter() {
	}

	public AbstractStarter(JSONObject config) {
		this.config = config;
	}

	
	@Override
	public abstract void execute(JSONObject data);


	@Override
	public void dispatch(Object data) {

		try {

			String type = config.getString("type");

			String threadName = config.getString("name");
			Thread.currentThread().setName(threadName);
			//212数据
			JSONObject dta = (JSONObject)data;

			JSONObject nodedata = dta.getJSONObject("nodedata");
			// 原始数据
			Object oriData = nodedata.get("message");

			String _id = UUID.randomUUID().toString().replace("-", "").toUpperCase();

			log.info("开始任务，ID：" + _id + "，原始数据：" + oriData);

			JSONArray steps = new JSONArray();
			JSONObject step = new JSONObject();
			JSONObject exp = new JSONObject();
			// 在这个循环里, 一条数据会沿着链, 层级处理
			for (NodeContainer node : nodes) {
				try {
					step = new JSONObject();
					step.put("node", node.bean.getName());
					step.put("startTime", DateUtil.getCurrentMilliTime());

					if (log.isDebugEnabled()) {
						log.debug("调试模式，ID：" + _id + "，节点数据：" + nodedata);
					}
					if (node.bean.isAsync()) {
						new Thread(() -> {
							try {
								// 异步处理
								node.execute(nodedata);
							} catch (Exception e) {
							}
						}, threadName).start();
					} else {
						// 同步处理
						node.execute(nodedata);
					}

					step.put("nodedata", JSON.parse(nodedata.toJSONString()));
					step.put("endTime", DateUtil.getCurrentMilliTime());
					steps.add(step);
				} catch (Exception e) {
					log.error("异常: {}", e.getMessage(), e );
					break;
				}
			}
			if (exp.isEmpty()) {
				log.info("执行完成，ID：" + _id);
			} else {
				log.info("执行异常，ID：" + _id);
			}

		} catch (Exception e) {

		}
	}
}
